import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { createPinia } from 'pinia'
import { ElMessage } from 'element-plus'

const pinia = createPinia()

/* ---------- 懒加载 ---------- */
const LoginView               = () => import('@/views/LoginView.vue')
const RegisterView            = () => import('@/views/RegisterView.vue')
const StudentRegister         = () => import('@/views/register/StudentRegister.vue')
const CoachRegister           = () => import('@/views/register/CoachRegister.vue')
const StudentDashboard        = () => import('@/views/dashboard/student/StudentDashboard.vue')
const CoachDashboard          = () => import('@/views/dashboard/coach/CoachDashboard.vue')
const AdminDashboard          = () => import('@/views/dashboard/admin/AdminDashboard.vue')
const StudentCoachCenter = () => import('@/views/dashboard/student/subpages/CoachQuery.vue')
const StudentMyCourses   = () => import('@/views/dashboard/student/subpages/MyCourses.vue')
const StudentPayment     = () => import('@/views/dashboard/student/subpages/PaymentCenter.vue')
const StudentMatchSignup = () => import('@/views/dashboard/student/subpages/MatchSignup.vue')
const CoachStudentManage = () => import('@/views/dashboard/coach/subpages/StudentManage.vue')
const CoachCourseAudit   = () => import('@/views/dashboard/coach/subpages/CourseAudit.vue')
const CoachCourseSchedule= () => import('@/views/dashboard/coach/subpages/CourseSchedule.vue')
const CoachMatchView     = () => import('@/views/dashboard/coach/subpages/MatchView.vue')
const StudentAdmin = () => import('@/views/dashboard/admin/subpages/StudentAdmin.vue')
const CoachAdmin   = () => import('@/views/dashboard/admin/subpages/CoachAdmin.vue')
const CampusManage = () => import('@/views/dashboard/admin/subpages/CampusManage.vue')
const AdminManage = () => import('@/views/dashboard/admin/subpages/AdminManage.vue')
const CourseAdmin  = () => import('@/views/dashboard/admin/subpages/CourseAdmin.vue')
const PaymentAdmin = () => import('@/views/dashboard/admin/subpages/PaymentAdmin.vue')
const MatchManage  = () => import('@/views/dashboard/admin/subpages/MatchManage.vue')
const SystemLog    = () => import('@/views/dashboard/admin/subpages/SystemLog.vue')
const NotFound                = () => import('@/views/dashboard/NotFound.vue')
const NoticeView = () => import('@/views/dashboard/NoticeView.vue')
const MyInfoView = () => import('@/views/dashboard/student/subpages/MyInfo.vue')
const CoachInfoView = () => import('@/views/dashboard/coach/subpages/CoachInfo.vue')
/* ---------- 路由表 ---------- */
const routes = [
    { path: '/',                 name: 'Login',      component: LoginView, meta: { title: '登录 - 乒乓球培训管理系统' } },
    { path: '/register',         name: 'Register',   component: RegisterView, meta: { title: '注册' } },
    { path: '/register/student', name: 'StudentRegister', component: StudentRegister, meta: { title: '学员注册' } },
    { path: '/register/coach',   name: 'CoachRegister',   component: CoachRegister, meta: { title: '教练注册' } },

    /* 学员仪表盘 */
    {
        path: '/dashboard/student',
        component: StudentDashboard,
        meta: { requiresAuth: true, userType: 'student' },
        children: [
            { path: 'coach-center',  name: 'StudentCoachCenter', component: StudentCoachCenter, meta: { title: '教练中心' } },
            { path: 'my-courses',    name: 'StudentMyCourses',   component: StudentMyCourses,   meta: { title: '我的课程' } },
            { path: 'payment-center',name: 'StudentPayment',     component: StudentPayment,     meta: { title: '缴费中心' } },
            { path: 'match-signup',  name: 'StudentMatchSignup', component: StudentMatchSignup, meta: { title: '月赛报名' } }
        ]
    },

    /* 教练仪表盘 */
    {
        path: '/dashboard/coach',
        component: CoachDashboard,
        meta: { requiresAuth: true, userType: 'coach' },
        children: [
            { path: 'student-manage',  name: 'CoachStudentManage',  component: CoachStudentManage, meta: { title: '我的学员' } },
            { path: 'course-audit',    name: 'CoachCourseAudit',    component: CoachCourseAudit,   meta: { title: '预约审批' } },
            { path: 'course-schedule', name: 'CoachCourseSchedule', component: CoachCourseSchedule,meta: { title: '我的课表' } },
            { path: 'match-view',      name: 'CoachMatchView',      component: CoachMatchView,     meta: { title: '赛事查看' } }
        ]
    },

    /* 管理员仪表盘 */
    {
        path: '/dashboard/admin',
        component: AdminDashboard,
        meta: { requiresAuth: true, userType: 'admin' },
        children: [
            {
                path: '',
                name: 'AdminDashboard',
                redirect: (to) => {
                    const authStore = useAuthStore(pinia)
                    const safeToken = typeof authStore.token === 'string' ? authStore.token : ''
                    return safeToken.trim() && authStore.user?.isSuperAdmin ? 'campus-manage' : 'student-admin'
                }
            },
            { path: 'student-admin',  name: 'AdminStudentAdmin',  component: StudentAdmin, meta: { title: '学员管理' } },
            { path: 'coach-admin',    name: 'AdminCoachAdmin',    component: CoachAdmin,   meta: { title: '教练管理' } },
            { path: 'campus-manage',  name: 'AdminCampusManage',  component: CampusManage, meta: { title: '校区管理', requireSuperAdmin: true } },
            { path: 'admin-manage',  name: 'AdminAllManage',  component: AdminManage, meta: { title: '管理员管理', requireSuperAdmin: true } },
            { path: 'course-admin',   name: 'AdminCourseAdmin',   component: CourseAdmin,  meta: { title: '课程管理' } },
            { path: 'payment-admin',  name: 'AdminPaymentAdmin',  component: PaymentAdmin, meta: { title: '缴费管理' } },
            { path: 'match-manage',   name: 'AdminMatchManage',   component: MatchManage,  meta: { title: '赛事管理' } },
            { path: 'system-log',     name: 'AdminSystemLog',     component: SystemLog,    meta: { title: '系统日志' } }
        ]
    },
    {
        path: '/notice',
        name: 'Notice',
        component: NoticeView,
        meta: { requiresAuth: true, title: '系统通知' }  // 三角色都能进
    },
    {
        path: '/dashboard/student/my-info',
        name: 'StudentMyInfo',
        component: MyInfoView,
        meta: { requiresAuth: true, userType: 'student', title: '我的信息' }
    },
    {
        path: '/dashboard/coach/my-info',
        name: 'CoachMyInfo',
        component: CoachInfoView,
        meta: { requiresAuth: true, userType: 'coach', title: '我的信息' }
    },

    { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound, meta: { title: '页面不存在' } }
]

/* ---------- 创建实例 ---------- */
const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes,
    scrollBehavior: () => ({ top: 0 })
})

/* ---------- 全局守卫 ---------- */
router.beforeEach((to, from, next) => {
    const authStore = useAuthStore(pinia)

    /* 0. 要去登录页，直接放行，不再做后续权限判断 */
    if (to.path === '/' || to.name === 'Login') {
        next()
        return
    }

    /* 1. 同步 localStorage → Pinia（仅非登录页） */
    const syncAuthFromLocalStorage = () => {
        try {
            const storedToken = localStorage.getItem('ptms-token')
            const storedUserStr = localStorage.getItem('ptms-user')
            if (!authStore.token && storedToken && storedUserStr) {
                const storedUser = JSON.parse(storedUserStr)
                if (storedUser.id) authStore.setAuth(storedToken, storedUser)
            }
        } catch {
            authStore.clearAuth()
        }
    }
    syncAuthFromLocalStorage()

    /* 2. 登录状态判定 */
    const isLoggedIn = () => {
        const validToken = typeof authStore.token === 'string' && authStore.token.trim().length > 30
        const validUser = typeof authStore.user === 'object' && authStore.user !== null && authStore.user.id
        return validToken && validUser
    }
    const loginStatus = isLoggedIn()

    /* 3. 设置页面标题 */
    document.title = to.meta.title || '乒乓球培训管理系统'

    /* 4. 角色校验 & 超级管理员校验 */
    if (to.meta.requiresAuth) {
        if (!loginStatus) {
            ElMessage.warning('请先登录')
            next({ path: '/', query: { redirect: to.fullPath }, replace: true })
            return
        }
        if (to.meta.userType && String(to.meta.userType).toLowerCase() !== String(authStore.user.userType).toLowerCase()) {
            ElMessage.error('角色权限不足')
            next({ path: getDefaultDashboard(authStore.user), replace: true })
            return
        }
        if (to.meta.requireSuperAdmin && !authStore.user.isSuperAdmin) {
            ElMessage.error('仅超级管理员可访问')
            next({ path: '/dashboard/admin/student-admin', replace: true })
            return
        }
    }
    next()
})

/* ---------- 工具函数 ---------- */
const getDefaultDashboard = (user) => {
    if (!user || typeof user !== 'object') return '/'
    const t = user.userType === 'studen' ? 'student' : user.userType
    switch (t) {
        case 'student': return '/dashboard/student/my-courses'
        case 'coach':   return '/dashboard/coach/course-schedule'
        case 'admin':   return user.isSuperAdmin ? '/dashboard/admin/campus-manage' : '/dashboard/admin/student-admin'
        default:        return '/'
    }
}

export default router